package com.itheima.socket.udp.demo04;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 * 使用MulticastSocket完成接收代码实现
 */
public class ReceiveDemo01 {

    public static void main(String[] args) throws IOException {

        /**
         * 步骤：
         * 1. 创建MulticastSocket对象(有参构造方法)
         * 2. 将该MulticastSocket加入到组播组
         * 3. 创建DatagramPacket数据包对象
         * 4. 调用MulticastSocket接收数据
         * 5. 解析数据
         * 6. 释放资源
         */
        // 创建MulticastSocket对象(有参构造方法)
        MulticastSocket multicastSocket = new MulticastSocket(9999) ;

        // 将该MulticastSocket加入到组播组: public void joinGroup(InetAddress mcastaddr)		加入一个特定的组播组
        InetAddress inetAddress = InetAddress.getByName("224.0.0.1");
        multicastSocket.joinGroup(inetAddress);

        while(true) {

            // 创建DatagramPacket数据包对象: public DatagramPacket(byte buf[], int length)
            byte[] bytes = new byte[1024] ;
            int length = bytes.length;
            DatagramPacket datagramPacket = new DatagramPacket(bytes , length) ;

            // 调用MulticastSocket接收数据
            multicastSocket.receive(datagramPacket);

            // 解析数据
            byte[] data = datagramPacket.getData();
            int packetLength = datagramPacket.getLength();
            System.out.println(new String(data , 0 , packetLength , "UTF-8"));

            // 离开组播组
            multicastSocket.leaveGroup(inetAddress);

        }

    }

}












